package com.zx.controller;

import com.alibaba.fastjson.JSON;
import com.zx.entity.Product;
import com.zx.service.ProductService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-03-11
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Resource
    private ProductService productService;

    /**
     * 查询商品信息
     *
     * @param id 商品id
     * @return 商品
     */
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public String findById(@PathVariable("id") Long id) {
//        try {
//            TimeUnit.SECONDS.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        Product product = productService.findById(id);
        return JSON.toJSONString(product);
    }


    /**
     * 添加商品
     *
     * @param product 商品实体
     * @return 商品
     */
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public String addProduct(@RequestBody Product product) {
        Product pro = productService.addProduct(product);
        return JSON.toJSONString(pro);
    }

    /**
     * 修改商品
     *
     * @param product 商品实体
     * @return 商品
     */
    @PutMapping
    @ResponseStatus(HttpStatus.CREATED)
    public String updateProduct(@RequestBody Product product) {
        Product pro = productService.updateProduct(product);
        return JSON.toJSONString(pro);
    }

    /**
     * 删除商品
     *
     * @param id 商品id
     */
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteProduct(@PathVariable("id") Long id) {
        productService.deleteById(id);
    }

}
